package org.autumn.cas;

import lombok.Data;
import sun.misc.Unsafe;


import java.lang.reflect.Field;

public class UnsafeUtil {

    private static Unsafe unsafe;

    static {
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            unsafe = (Unsafe) theUnsafe.get(null);
        } catch (Exception e) {

        }
    }

    public static Unsafe getUnsafe() {
        return unsafe;
    }

    public static void main(String[] args) throws NoSuchFieldException {
        Teacher teacher = new Teacher();
        Unsafe unsafe = getUnsafe();
        // 获取偏移地址
        long idOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("id"));
        unsafe.compareAndSwapInt(teacher, idOffset, 0, 1);

        System.out.println(teacher);
    }
}

@Data
class Teacher {
    volatile int id;
}